package biz.ezcom.hibernate.test;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import biz.ezcom.hibernate.pojo.UserAssigned;
import biz.ezcom.hibernate.pojo.UserIdentity;
import biz.ezcom.hibernate.pojo.UserUUID;

public class Client {
	
	@Test
	public void testSessionUUID(){
		Session session = null;
		Transaction tx = null;
		try{
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			
			UserUUID uuid = new UserUUID();
			uuid.setName("uuid");
			uuid.setPassword("uuid");
			uuid.setCreateTime(new Date(0));
			uuid.setExpireTime(new Date());
			
			session.save(uuid);
			session.flush();	//此时清理缓存,发SQL
			
			uuid.setName("uuidUpdate");	//persistence状态对象,session管理了,状态改变,commit时会update
			session.update(uuid);				//没有实际意义
			session.evict(uuid);					//此时uuid从session的缓存中清除

			tx.commit();	//commit时,session无对象,不发SQL
		}catch(Exception e){
			tx.rollback();
			e.printStackTrace();
		}finally{
			HibernateUtil.closeSession(session);
		}
	}
	
	@Test
	public void testSessionIdentity(){
		Session session = null;
		Transaction tx = null;
		try{
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			
			UserIdentity identity = new UserIdentity();
			identity.setName("identity");
			identity.setPassword("identity");
			identity.setCreateTime(new Date(0));
			identity.setExpireTime(new Date());
			
			session.save(identity);	//主键为:identity,save时发SQL 
			
			tx.commit();
		}catch(Exception e){
			tx.rollback();
			e.printStackTrace();
		}finally{
			HibernateUtil.closeSession(session);
		}
	}
	@Test
	public void testSessionAssigned(){
		Session session = null;
		Transaction tx = null;
		try{
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			
			UserAssigned assigned = new UserAssigned();
			assigned.setId("assigned");
			assigned.setName("assigned");
			assigned.setPassword("assigned");
			assigned.setCreateTime(new Date(0));
			assigned.setExpireTime(new Date());
			
			session.save(assigned);	//此时assigned被加入session的缓存中
			
			tx.commit();	//commit时,没有SQL
		}catch(Exception e){
			tx.rollback();
			e.printStackTrace();
		}finally{
			HibernateUtil.closeSession(session);
		}
	}
	
}
